package cn.tedu.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * JDBC执行查询语句[DQL];
 * 查询所有用户的用户名、密码、年龄;
 * SELECT username, password, age FROM userinfo
 */
public class JDBCDemo5 {
    public static void main(String[] args) {
        //try(); 自动关闭特性,当try中代码执行完毕后,会自动调用该对象的close()方法;
        //断开数据库的连接,不用再connection.close()手动断开连接了;
        try (Connection connection = DBUtil.getConnection();){
            Statement statement = connection.createStatement();
            String sql = "SELECT username,password,age FROM userinfo";
            //resultSet:存放SQL语句的查询结果;
            ResultSet r = statement.executeQuery(sql);
            //获取数据
            /*
                r.next():判断是否存在下一条记录
                指针的起始位置,在第一个元素之前;
                  1.存在:返回true,指针向后移动一位;
                  2.不存在:返回false;
             */
            while (r.next()){
                String username = r.getString("username");
                String password = r.getString("password");
                int age = r.getInt("age");
                System.out.println(username + "-" + password + "-" + age);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}












